
export const task2 = function () {
    let once = false;
    let oldvalue;
    let id = 1;
    let queue = [];
    let willSendData = {
        asks: [],
        bids: [],
    };
    let postData = {
        asks: [],
        bids: [],
        asksFilter: '',
        bidsFilter: '',
        contractCode: '',

    }
    let intervalTime = null;
    // compare  排序
    const debug = false;
    const log = {
        print: function (s) {
            if (debug) {
                console.log(s)
            }
        },
    }

    function compare(array, key, type = 'asc') {
        return array.sort(function (a, b) {
            if (type === 'asc') {  //降序
                return b[key] - a[key]
            } else { //升序
                return a[key] - b[key]
            }

        })
    }
    //处理数据的函数  去重
    function handleArray(data) {
        let flag = {

        }
        /**
         *  exist: 0
            orderPrice: "10262.0"
            orderQuantity: 58175
            orderQuantityShow: "58,175"
            priceD: 10262
         */
        const newArr = [];
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            const key = item.orderPrice;
            if (!flag[`${key}`] && item.orderQuantity > 0) {
                flag[`${key}`] = true;
                newArr.push(item);
            }
        }
        return newArr;
    }
    function numFormat(num) {
        const c = (num.toString().indexOf('.') !== -1) ? num.toLocaleString() : num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
        return c;
    }
    //computedSum 
    function computedSum(array, type) {
        let new_array = [];
        const last = array.length - 1;
        if (type === '1') {
            new_array = array.slice(last - 7, last + 1);
        } else {
            new_array = array.slice(0, 8);
        }


        const len = new_array.length - 1;
        if (type === '1') {
            for (let index = len; index >= 0; index--) {
                const element = new_array[index]; //item
                if (index === len) {
                    element['sum'] = element.orderQuantity;  //最后一个是等于当前值的

                } else {
                    element['sum'] = element.orderQuantity + new_array[index + 1].sum;
                }
                element['amount'] = element.orderQuantity;
                element['amountShow'] = numFormat(element.orderQuantity);
                element['price'] = element.orderPrice;
                element['type'] = type;

            }
        }

        if (type === '2') {
            for (let index = 0; index <= len; index++) {
                const element = new_array[index]; //item
                if (index === 0) {
                    element['sum'] = element.orderQuantity;  //最后一个是等于当前值的

                } else {
                    element['sum'] = element.orderQuantity + new_array[index - 1].sum;
                }
                element['amount'] = element.orderQuantity;
                element['amountShow'] = numFormat(element.orderQuantity);
                element['price'] = element.orderPrice;
                element['type'] = type;

            }
        }

        return new_array;
    }
    /**
     * 处理数据
     * @param {*} cacheData 
     * @param {*} oldvalue 
     */
    function handleData(cacheData, oldvalue_temp) {
        //oldvalue_temp  是一个深克隆的变量
        //去除重复的价格
        //   log.print(new Date().getTime())
        const { asks, bids } = oldvalue_temp;  

        const newAsks = handleArray([].concat(cacheData.asks, asks))  //合并去重
        const newBids = handleArray([].concat(cacheData.bids, bids)); //合并去重
        const compareAsks = compare(newAsks, 'orderPrice', 'asc'); //排序
        const compareBids = compare(newBids, 'orderPrice', 'asc'); //排序
        //重新赋值
        // cacheData.asks  = compareAsks
        // cacheData.bids = compareBids;
        oldvalue_temp.asks = compareAsks;
        oldvalue_temp.bids = compareBids;
        //修改缓存里面的值
        oldvalue = oldvalue_temp ; //修改全局缓存变量的值
        // log.print(oldvalue)
        //将要发送的数据
        willSendData['asks'] = computedSum(oldvalue.asks, '1') //切片计算sum
        willSendData['bids'] = computedSum(oldvalue.bids, '2');//切片计算sum

        //  const len = cacheData.asks.length;
        //const price = cacheData.asks[len-1].price;

        // cacheData.bids = cacheData.bids.filter(item=>{

        //     return item.price < price;
        // })
        //   cacheData.bids =  cacheData.bids.splice(0,8);
        // log.print(cacheData)
        // log.print(new Date().getTime())
        return willSendData;
    }
    // 纠错处理
    /**
     * 盘口自动纠错逻辑
     * 1.新收到的每条盘口数据，都要和当前旧的盘口的买一或者卖一做比较。
     * 2.遍历新收到的每条买盘数据，如果新收到的bid价格，大于等于当前旧盘口的卖一价格，那么需要删除当前旧盘口里面的卖一
     * 3.遍历新收到的每条卖盘数据，如果新收到的ask价格，小于等于当前旧盘口的买一价格，那么需要删除当前旧盘口里面的买一
     * @param {*} commintData_temp 
     * @param {*} oldvalue_temp 
     */
    function errorCorrection(commintData_temp, oldvalue_temp) {
        //  log.print(oldvalue_temp)
        const asksPrice = oldvalue_temp.asks[0].orderPrice;
        log.print('纠错前 ask oldvalue_temp = '+oldvalue_temp)
        log.print(oldvalue_temp)
        log.print('asksPrice 价格 = '+asksPrice)
        commintData_temp.bids.forEach(element => {
            log.print('current price = '+element.orderPrice +'  asksPrice='+asksPrice)
            if (element.orderPrice >= asksPrice) {
                oldvalue_temp.asks.splice(0, 1);
            }
        });

        log.print('纠错后 oldvalue_temp = '+oldvalue_temp)
        log.print(oldvalue_temp)
        log.print('纠错前 ask bidsPrice = '+oldvalue_temp)
        log.print(oldvalue_temp)
        const bidsPrice = oldvalue_temp.bids[0].orderPrice;
        log.print('bidsPrice 价格 = '+bidsPrice)
        commintData_temp.asks.forEach(element => {
            log.print('current price = '+element.orderPrice +'  bidsPrice='+bidsPrice)
            if (element.orderPrice <= bidsPrice) {
                oldvalue_temp.bids.splice(0, 1);
            }
        });

        log.print('纠错后 oldvalue_temp = '+oldvalue_temp)
        log.print(oldvalue_temp)
        return oldvalue_temp;
    }

    function printEnv() {
        //  log.print(oldvalue);
        //  log.print(willSendData)
        //  log.print(id)
    }
    //消费queue 里面的数据
    function composeArr(a, b, c) {

        return a.concat(b)

    }
    function consumptionQueue(len) {
        //合并改变的数据
        if (len <= 0) {
            console.log('queue leng <=0');
            return { ok: false, res: null };
        }
        const asks = []; //纠错过后的ask
        const bids = [];// //纠错过后的bids
        let asksFilter;
        let bidsFilter;
        log.print(len - 1)
        for (let index = len - 1; index >= 0; index--) {
            const element = queue[index];
            log.print(index)
            if (index === len - 1) {
                asksFilter = element.asksFilter  //取最新的asksFilter
                bidsFilter = element.bidsFilter;//取最新的bidsFilter
            }

            asks.push(element.asks);
            bids.push(element.bids);
        }
        log.print(asks)
        log.print(bids)
        let mergeAsks = asks.reduce(composeArr, []);
        let mergeBids = bids.reduce(composeArr, [])
        //  数据去重
        log.print(mergeAsks)
        log.print(mergeBids)
        mergeAsks = handleArray(mergeAsks); //去重
        mergeBids = handleArray(mergeBids); //去重


        //去重

        queue.splice(0, len);  //删除
        log.print('消费 ' + len + '个数据' + ' ' + 'delete ' + len + '个数据');
        log.print('新的queue 的数据=' + queue);

        return {
            ok: true, res: {
                bids: mergeBids,
                asks: mergeAsks,
                asksFilter,
                bidsFilter,
            },
        }
    }
    // eslint-disable-next-line no-restricted-globals
    self.onmessage = function (e) {
        //  log.print('on message')
        const { res: comming, oldvalue: medelV } = e.data;

        //大于8 的时候默认为不是初次的数据 要缓存起来
        if (medelV && medelV.asks && medelV.asks.length > 8 &&  medelV.bids &&  medelV.bids.length > 8) {
            //  log.print('http 请求来的数据', medelV)
            medelV.asks = compare(medelV.asks, 'orderPrice', 'asc')  //升序排序
            medelV.bids = compare(medelV.bids, 'orderPrice', 'asc') //升序排序
            oldvalue = medelV;
        }
        log.print('old value 的值')
        log.print(oldvalue)
        const commintData = comming.data;  //ws  更新的数据  ws 推送过来的数据
        queue.push(commintData);    //新数据添加到队列里面
        //首先要进行纠错处理
        log.print('=======')
        log.print(queue)
        log.print('=======')
        const commintasks = commintData.asks;

        const commintbids = commintData.bids;
        postData = {
            asks: commintasks,
            bids: commintbids,
            asksFilter: commintData.asksFilter,
            bidsFilter: commintData.bidsFilter,
            contractCode: commintData.contractCode,
        }

        // queue.push(e.data);


        if (!once) {
            intervalTime = setInterval(() => {
                // log.print(new Date().getTime())

                const { ok, res: mergeComminDate } = consumptionQueue(queue.length);
                if (!ok) {
                    log.print('发生异常!');
                    return ;
                }
                log.print(mergeComminDate)
                const  clone_mergeComminDate = Object.assign({},mergeComminDate)
                const clone_oldvalue = Object.assign({}, oldvalue)
                const oldvalue_temp = errorCorrection(clone_mergeComminDate, clone_oldvalue); //纠错不会改变mergeComminDate 
                willSendData = handleData(clone_mergeComminDate, Object.assign({},oldvalue_temp));
                willSendData.id = id;
                log.print(queue.length)
                log.print('end===========================')
                log.print(oldvalue)
                log.print('end===========================')
                id++;
                console.log(willSendData)
                const blob = new Blob([JSON.stringify(willSendData)]);

                postMessage(blob);
            }, 300);
            once = true;  //首次已经完成
        }
    }
}







// function hanldeData(data){
//     const Mapping = (result = []) => {
//         return result.map((item = {}) => {
//           const { orderPrice, orderQuantity, orderQuantityShow } = item;
//           return {
//             price: orderPrice,
//             amount: orderQuantity,
//             amountShow: orderQuantityShow,
//             ...item,
//           };
//         });
//       };
//       result.asks = Mapping(result.asks); // 取到对应的买卖数据
//       result.bids = Mapping(result.bids);
//       let asks = [...(ensure_records.asks ? ensure_records.asks : [])]; // 判断是之前是否存在数据
//       let bids = [...(ensure_records.bids ? ensure_records.bids : [])];
//       const Filtering = (result = [], side = []) => {
//         result.forEach((item = {}) => {
//           const filterOne = _.findIndex(
//             side,
//             (one = {}) => String(one.price) === String(item.price)
//           );
//           if (filterOne !== -1) {
//             side.splice(filterOne, 1, item);
//           } else {
//             side.push(item);
//           }
//         });
//       };
//       if (_.has(result, 'asks')) {
//         Filtering(result.asks, asks);
//       }
//       if (_.has(result, 'bids')) {
//         Filtering(result.bids, bids);
//       }

//       const remove = result =>
//         _.remove(result, (item = {}) => Number(item.amount) !== 0);

//       result = {
//         asks:
//           _.orderBy(remove(asks), item => Number(item.price), ['desc']) || [],
//         bids:
//           _.orderBy(remove(bids), item => Number(item.price), ['desc']) || [],
//       };

//       result.asks.forEach((item, index) => {
//         item.type = '1';
//         item.sum = _.sumBy(
//           result.asks.slice(index, result.asks.length),
//           ({ amount = 0 } = {}) => Number(amount)
//         );
//       });
//       result.bids.forEach((item, index) => {
//         item.type = '2';
//         item.sum = _.sumBy(
//           result.bids.slice(0, index + 1),
//           ({ amount = 0 } = {}) => Number(amount)
//         );
//       });
// }

